﻿<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="QH.aspx.cs" Inherits="InnovationFoundry.QualityHelper.Web.Pages.QualityHelper" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
<!--
// This File is part of Innovation Foundry's "QualityHelper Project"
//
// Copyright  2008 Innovation Foundry Pty Ltd
// All rights reserved
//
// This work is free software; you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published 
// by the Free Software Foundation; either version 3 of the License, 
// or any later version. This work is distributed in the hope that 
// it will be useful, but WITHOUT ANY WARRANTY; without even the 
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
// PURPOSE. 
// See version 3 of the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this work; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA  02110-1301 USA
// or alternatively it may be downloaded from <http://www.gnu.org/licenses/>.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head runat="server">
    <script type="text/javascript" src="Silverlight.js"></script>
	<script src="prototype/prototype.js" type="text/javascript"></script>
	<script src="google_tools.js" type="text/javascript"></script>
	<script src="if_tools.js" type="text/javascript"></script>
	<script src="qualityhelper_classes.js" type="text/javascript"></script>
	<script src="gears_init.js" type="text/javascript"></script>
	<script type="text/javascript">
	    //Preload
	    var hasGears = checkForGears('Welcome From QualityHelper', escape(location.href));
	</script>
	<script src="data_manager.js" type="text/javascript"></script>
	<script type="text/javascript">
	    //Post Load, cache minimum docs
	    if (hasGears) {
	        InnovationFoundryJS.DataManager.cache_internal_documents();
	    }
	    else {
	        alert('Gears not found. This is a requirement.');
	    }
        //alert('this illustrates the cache, how to add to it (a few bugs in ie/firefox sorry), bound stuff in page.xaml.cs and here');
        //InnovationFoundryJS.DataManager.cache_documents('./DocReader.axd?DocID=6');
	    
	    //use F11 instead
	    function fullScreen(theURL) {
	        window.open(theURL, '', 'fullscreen=yes, width="110%", height="100%", menubar=no, toolbar=no, scrollbars=no, resizable=no');
	    }
	</script>
    <style type="text/css">
    html, body {
	    height: 100%;
	    overflow: auto;
    }
    body {
	    padding: 0;
	    margin: 0;
    }
    #silverlightControlHost {
	    height: 100%;
    }
    </style>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {

            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }
            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }
    </script>
    <title>QualityHelper</title>
</head>
<body style="background-color:Black;height:100%;margin:0;color:White;">
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager" runat="server">
            <Services>
                <asp:ServiceReference Path="~/QualityHelperDataService.svc" />
            </Services>
        </asp:ScriptManager>
<%--        <div id="silverlight_div"  style="height:100%;">
            <asp:Silverlight ID="QualityHelperSilverlightControl" runat="server" Source="" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
        </div>--%>
        <div id="silverlight_div">
		    <object ID="QualityHelperSilverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
			<param name="source" value="ClientBin/QualityHelperBaseSilverlight.xap"/>
			<param name="onerror" value="onSilverlightError" />
			<param name="background" value="black" />
			<param name="minRuntimeVersion" value="2.0.31005.0" />
			<param name="autoUpgrade" value="true" />
			<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
     			<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
			</a>
		</object>
		<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
        </div>
        <div id="status" style="display:inline;"><p style="text-decoration: blink;">Loading...</p></div>
        <script language="javascript" type="text/javascript">

            function LoadMainSilverlightControl() {
                clearStatus();
                LoadSilverlightControl('./ClientBin/QualityHelperBaseSilverlight.xap', 'QualityHelperSilverlightControl', 'silverlight_div');
            }

            function HideMainSilverlightControl() {
                HideSilverlightControl('QualityHelperSilverlightControl', 'silverlight_div');
            }

            function IsOnline() {
                try {
                    return !InnovationFoundryJS.DataManager.localStore.enabled;
                }
                catch (e) {
                    return false;
                }
            }

            function GetApplicationBG() {
                try {
                    return InnovationFoundryJS.DataManager.ApplicationBackground;
                }
                catch (e) {
                    return null;
                }
            }

            function GetApplicationAlias() {
                try {
                    return InnovationFoundryJS.DataManager.ApplicationAlias;
                }
                catch (e) {
                    return null;
                }
            }

            function GetApplicationIcon() {
                try {
                    return InnovationFoundryJS.DataManager.ApplicationIcon;
                }
                catch (e) {
                    return null;
                }
                
            }

            function getWindowHeight() {
                var windowHeight = 0;
                if (typeof (window.innerHeight) == 'number') {
                    windowHeight = window.innerHeight;
                }
                else {
                    if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                    }
                    else {
                        if (document.body && document.body.clientHeight) {
                            windowHeight = document.body.clientHeight;
                        }
                    }
                }
                return windowHeight;
            }

            function getWindowWidth() {
                var windowWidth = 0;
                if (typeof (window.innerWidth) == 'number') {
                    windowWidth = window.innerWidth;
                }
                else {
                    if (document.documentElement && document.documentElement.clientWidth) {
                        windowWidth = document.documentElement.clientWidth;
                    }
                    else {
                        if (document.body && document.body.clientWidth) {
                            windowWidth = document.body.clientWidth;
                        }
                    }
                }
                return windowWidth;
            }
            
            //JAVASCRIPT DATA SYNC (LAYER)
            //Cache Methods - Reliant on the QualityHelperDataService
            function downloadFailed(result, userContext, methodName) {
                trace('Failed:' + methodName);
            }

            function serverContactFailed(result, userContext, methodName) {
                trace('Failed:' + methodName);
                //Can go offline, or notify of something here
            }

            function ClearAllDocuments() {
                try {
                    InnovationFoundryJS.DataManager.store_clear();
                }
                catch (e) {
                    var StoreName = 'qualityhelper-store';
                    this.localServer = google.gears.factory.create('beta.localserver');
                    this.localServer.removeStore(StoreName);
                    this.localStore = this.localServer.createStore(StoreName);
                }
            }

            function GetRootProcedureID() {
                return InnovationFoundryJS.DataManager.get_rootprocedureid();
            }   

            function ResetDB() {
                InnovationFoundryJS.DataManager.db_reset();
            }

            function GetDate_ServerTime() {
                try {
                    InnovationFoundryJS.DataManager.localStore.enabled = true;
                     if (isDefined(typeof QualityHelperDataService))
                        QualityHelperDataService.GetDate_ServerTime(GetDate_ServerTimeSucceeded, serverContactFailed, null);
                    else
                        LoadMainSilverlightControl();
                }
                catch (e) {
                    alert('couldn\'t load');
                }
            }

            var serverTime = 0;
            function GetDate_ServerTimeSucceeded(result, userContext, methodName) {
                //OK The server is up
                //Now compare dates to ours and reset DB if required
                serverTime = result;
                GetDateChanged_Procedures();
            }

            var serverChangedDiagrams = 0;
            function GetDateChanged_Procedures() {
                var date = (new Date()).toString();
                QualityHelperDataService.GetDateChanged_Procedures(GetDateChanged_ProceduresSucceeded, downloadFailed, date);
            }
            function GetDateChanged_ProceduresSucceeded(result, userContext, methodName) {
                //OK The server is up
                //Now compare dates to ours and reset DB if required
                serverChangedDiagrams = result;
                CheckForDiagramUpdates();
            }
            function CheckForDiagramUpdates() {
                var lastDownloadedDiagrams = InnovationFoundryJS.DataManager.db_selectDateTime_diagrams();
                //alert('diagrams:\n' + lastDownloadedDiagrams + '\n' + serverChangedDiagrams);
                if (serverChangedDiagrams > lastDownloadedDiagrams) {
                    createShortcut();
                    GetAll();
                    //Now insert into TT
                    InnovationFoundryJS.DataManager.db_update_latestDiagrams(serverChangedDiagrams);
                }
                else {
                    //Start the app
                    LoadMainSilverlightControl();
                    //Try and download cache
                    GetDateChanged_Documents();
                }
            }

            var serverChangedDocuments = 0;
            function GetDateChanged_Documents() {
                QualityHelperDataService.GetDateChanged_Documents(GetDateChanged_DocumentsSucceeded, downloadFailed, null);
            }
            function GetDateChanged_DocumentsSucceeded(result, userContext, methodName) {
                //OK The server is up
                //Now compare dates to ours and reset DB if required
                serverChangedDocuments = result;
                var lastDownloadedDocumentsFull = InnovationFoundryJS.DataManager.db_selectDateTime_documentsFull();
                //alert(serverChangedDocuments + '\n' + lastDownloadedDocumentsFull);

                //var lastDownloadedDocumentsIncremental = InnovationFoundryJS.DataManager.db_selectDateTime_documentsIncremental();
                if (serverChangedDocuments > lastDownloadedDocumentsFull) {
                    GetSubset_DocumentCache(lastDownloadedDocumentsFull);
                }
            }


            var updatesCompleted = 0;
            function AddMethodCompleted(method) {
                updatesCompleted++;
                if (updatesCompleted == 22) {
                    addStatus('Completed Update. (Hit refresh <F5> if the page does not reload.)');
                    window.location.replace(unescape(window.location.pathname));
                }
                addStatus(method);
            }

            function GetAll() {
                ResetDB();
                GetAll_Purpose();
                GetAll_ConnectionType();
                GetAll_Connects();
                GetAll_Document();
                GetAll_DocumentType();
                //GetAll_File();
                GetAll_GroupHierarchy();
                GetAll_Group();
                GetAll_MimeExtensions();
                GetAll_MimeType();
                GetAll_Participants();
                GetAll_PolicyHierarchy();
                GetAll_Policy();
                GetAll_ProcedureAliases();
                GetAll_ProcedureCompliance();
                GetAll_ProcedureDocuments();
                GetAll_ProcedureGroup();
                GetAll_Procedure();
                GetAll_System();
                GetAll_SystemPolicy();
                GetAll_TranslateTable();
                GetAll_User();
                GetAll_References();
            }

            function GetAll_Purpose() {
                QualityHelperDataService.GetAll_Purpose(GetAll_PurposeSucceeded, downloadFailed, null);
            }            
            function GetAll_PurposeSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_purpose(result[i].purposeName, result[i].flowchartElement);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   

            function GetAll_ConnectionType()
            {
                QualityHelperDataService.GetAll_ConnectionType(GetAll_ConnectionTypeSucceeded, downloadFailed, null);
            }
            function GetAll_ConnectionTypeSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_connectionType(result[i].connectionType, result[i].colorRGBHex);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_Connects()
            {
                QualityHelperDataService.GetAll_Connects(GetAll_ConnectsSucceeded, downloadFailed, null);
            }
            function GetAll_ConnectsSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_connects(result[i].procedureOrigin, result[i].procedureDestination, result[i].connectionType);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   

           
            function GetAll_Document()
            {
                QualityHelperDataService.GetAll_Document(GetAll_DocumentSucceeded, downloadFailed, null);
            }
            function GetAll_DocumentSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_document(result[i].documentID, result[i].md5Checksum, result[i].dateUpdated, result[i].documentExtension, result[i].originUrl, result[i].documentName, result[i].documentDescription, result[i].imageURL, null);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   

            function GetAll_DocumentCache() {
                QualityHelperDataService.GetAll_DocumentCache(GetAll_DocumentCacheSucceeded, downloadFailed, null);
            }
            function GetSubset_DocumentCache(longDateTimeString) {
                QualityHelperDataService.GetSubset_DocumentCache(longDateTimeString, GetAll_DocumentCacheSucceeded, downloadFailed, null);
            }
            function GetAll_DocumentCacheSucceeded(result, userContext, methodName) {
                //MAKE SURE THIS IS RUN AFTER DOCUMENT INSERT!
                //Only updates (no inserts)
                InnovationFoundryJS.DataManager.db_transaction_start();
                var dateUpdated = 0;
                for (var i = 0; i < result.length; i++) {
                    if (result[i].dateUpdated > dateUpdated)
                        dateUpdated = result[i].dateUpdated;
                    InnovationFoundryJS.DataManager.db_update_document_cache(result[i].documentID, result[i].documentVersion, result[i].md5Checksum, result[i].dateUpdated, result[i].documentText);
                    if (result[i].documentFileID != null && result[i].documentFileID.length > 0) {
                        //TODO: Could put this in a worker to improve performance, does it asynchronously anyway
                        InnovationFoundryJS.DataManager.cache_documents('./DocReader.axd/' + result[i].documentID);
                    }
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                //Now update TT
                if (dateUpdated > 0)
                    InnovationFoundryJS.DataManager.db_update_lastFullDocuments(dateUpdated);
            }   

            function GetAll_DocumentType()
            {
                QualityHelperDataService.GetAll_DocumentType(GetAll_DocumentTypeSucceeded, downloadFailed, null);
            }
            function GetAll_DocumentTypeSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_documentType(result[i].documentType, result[i].imageURL);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }

            function GetAll_File() {

                throw new Error('Caching of files not handled this deep. GetAll_DocumentCache in charge.');
                //QualityHelperDataService.GetAll_File(GetAll_FileSucceeded, downloadFailed, null);
            }

            function GetAll_GroupHierarchy()
            {
                QualityHelperDataService.GetAll_GroupHierarchy(GetAll_GroupHierarchySucceeded, downloadFailed, null);                
            }
            function GetAll_GroupHierarchySucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_groupHierarchy(result[i].parentGroupName, result[i].childGroupName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_Group()
            {
                QualityHelperDataService.GetAll_Group(GetAll_GroupSucceeded, downloadFailed, null);
            }
            function GetAll_GroupSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_group(result[i].groupName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_MimeExtensions()
            {
                QualityHelperDataService.GetAll_MimeExtensions(GetAll_MimeExtensionsSucceeded, downloadFailed, null);
            }
            function GetAll_MimeExtensionsSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_mimeExtensions(result[i].documentExtension, result[i].mimeType);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   


            function GetAll_MimeType()
            {
                QualityHelperDataService.GetAll_MimeType(GetAll_MimeTypeSucceeded, downloadFailed, null);
            }
            function GetAll_MimeTypeSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_mimeType(result[i].mimeType, result[i].documentType);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }               

            function GetAll_Participants()
            {
                QualityHelperDataService.GetAll_Participants(GetAll_ParticipantsSucceeded, downloadFailed, null);
            }
            function GetAll_ParticipantsSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_participants(result[i].username, result[i].groupName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }      
            
            function GetAll_PolicyHierarchy()
            {
                QualityHelperDataService.GetAll_PolicyHierarchy(GetAll_PolicyHierarchySucceeded, downloadFailed, null);
            }
            function GetAll_PolicyHierarchySucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_policyHierarchy(result[i].parentPolicyName, result[i].childPolicyName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_Policy()
            {
                QualityHelperDataService.GetAll_Policy(GetAll_PolicySucceeded, downloadFailed, null);
            }
            function GetAll_PolicySucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_policy(result[i].policyName, result[i].policyDescription);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_ProcedureAliases()
            {
                QualityHelperDataService.GetAll_ProcedureAliases(GetAll_ProcedureAliasesSucceeded, downloadFailed, null);
            }
            function GetAll_ProcedureAliasesSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_procedureAliases(result[i].procedureID, result[i].alias);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            

            function GetAll_ProcedureCompliance()
            {
                QualityHelperDataService.GetAll_ProcedureCompliance(GetAll_ProcedureComplianceSucceeded, downloadFailed, null);
            }
            function GetAll_ProcedureComplianceSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_procedureCompliance(result[i].procedureID, result[i].policyName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_ProcedureDocuments()
            {
                QualityHelperDataService.GetAll_ProcedureDocuments(GetAll_ProcedureDocumentsSucceeded, downloadFailed, null);
            }
            function GetAll_ProcedureDocumentsSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_procedureDocuments(result[i].procedureID, result[i].documentID);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
            function GetAll_ProcedureGroup()
            {
                QualityHelperDataService.GetAll_ProcedureGroup(GetAll_ProcedureGroupSucceeded, downloadFailed, null);
            }
            function GetAll_ProcedureGroupSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_procedureGroup(result[i].procedureID, result[i].groupName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }               

            function GetAll_Procedure()
            {
                QualityHelperDataService.GetAll_Procedure(GetAll_ProcedureSucceeded, downloadFailed, null);
            }
            function GetAll_ProcedureSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_procedure(result[i].procedureID, result[i].procedureName, result[i].procedureDescription, result[i].purposeName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }  
            
            function GetAll_System()
            {
                QualityHelperDataService.GetAll_System(GetAll_SystemSucceeded, downloadFailed, null);
            }
            function GetAll_SystemSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_system(result[i].systemName, result[i].systemDescription);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }  
            
            function GetAll_SystemPolicy()
            {
                QualityHelperDataService.GetAll_SystemPolicy(GetAll_SystemPolicySucceeded, downloadFailed, null);
            }
            function GetAll_SystemPolicySucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_systemPolicy(result[i].systemName, result[i].policyName);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }              

            function GetAll_TranslateTable()
            {
                QualityHelperDataService.GetAll_TranslateTable(GetAll_TranslateTableSucceeded, downloadFailed, null);
            }
            function GetAll_TranslateTableSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_translateTable(result[i].ttKey, result[i].ttSupplement, result[i].ttObjectType, result[i].ttValue, result[i].isPrivate, result[i].isReadOnly);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }     

            function GetAll_User()
            {
                QualityHelperDataService.GetAll_User(GetAll_UserSucceeded, downloadFailed, null);
            }
            function GetAll_UserSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_user(result[i].username);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }

            function GetAll_References() {
                QualityHelperDataService.GetAll_References(GetAll_ReferencesSucceeded, downloadFailed, null);
            }
            function GetAll_ReferencesSucceeded(result, userContext, methodName) {
                InnovationFoundryJS.DataManager.db_transaction_start();
                for (var i = 0; i < result.length; i++) {
                    InnovationFoundryJS.DataManager.db_insert_references(result[i].procedureOrigin, result[i].procedureDestination);
                }
                InnovationFoundryJS.DataManager.db_transaction_commit();
                AddMethodCompleted(methodName);
            }   
            
        </script>
         <script language="javascript" type="text/javascript">
             function bob() {
                 var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                 QualityHelperControl.content.SilverlightQualityHelper.AddSearchResult('BOOFOO');

             }

             function fill() {
                 var nav = document.getElementById("QualityHelperSilverlightControl");
                 nav.content.SilverlightQualityHelper.fill();
             }

             function createShortcut() {
                 var desktop = google.gears.factory.create("beta.desktop");
                 var progName = GetApplicationAlias();
                 var description = "This shortcut launches " + progName + ".";
                 var icons = {
                     "32x32": "qh32.png",
                     "48x48": "qh48.png",
                     "128x128": "qh128.png"
                 };

                 desktop.createShortcut(progName,  // name
                         "QH.aspx",  // url
                         icons,  // icons (must specify at least one)
                         description);  // description (optional)
             }             
             
             function alice(msg) {
                 alert(msg);
             }

             function updateDocuments(procedureID) {
                 //Could add in worker thread here to do this
                 var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                 QualityHelperControl.content.SilverlightQualityHelper.UpdateDocumentsCallback(InnovationFoundryJS.DataManager.db_select_documents(procedureID), procedureID);
             }

             function getProcedureDiagram(procedureID) {
                 var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                 InnovationFoundryJS.DataManager.db_update_lastProcedureClicked(procedureID);
                 QualityHelperControl.content.SilverlightQualityHelper.GetProcedureDiagramCallback(InnovationFoundryJS.DataManager.parse_diagram(procedureID));
            }

            function getLastProcedureClicked() {
                return InnovationFoundryJS.DataManager.db_select_lastProcedureClicked();
            }

            function getProcedureParents(procedureID) {
                var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                QualityHelperControl.content.SilverlightQualityHelper.GetProcedureParentsCallback(InnovationFoundryJS.DataManager.db_select_procedureConnectionsParents(procedureID), procedureID);
            }

            function getProcedures(procedureStringArray) {
                return InnovationFoundryJS.DataManager.db_select_procedures(procedureStringArray.split('||||'));
            }                
            
            
            function switchMode() {
                 if (hasGears) {
                     if (InnovationFoundryJS.DataManager.localStore.enabled == false) {
                         //Data
                         InnovationFoundryJS.DataManager.localStore.enabled = true;
                     }
                     else {
                         InnovationFoundryJS.DataManager.localStore.enabled = false;
                     }
                     alert('browser offline: ' + InnovationFoundryJS.DataManager.localStore.enabled);
                 }

             }   
             
             
             function openDocument(documentID) {
                 // alert('this illustrates the cache, how to get to it');
                 //window.location.replace('./DocReader.axd?DocID=' + documentID);
                 document.getElementById('downloader').src = './DocReader.axd/' + documentID;
             }
             

                
             function getFileViaGears(docID) {
                var request = google.gears.factory.create('beta.httprequest');
                request.open('GET', './DocReader.axd/' + docID);
                alert('testing blob started');
                request.onreadystatechange = function() {
                    alert(request.readyState);
                    if (request.readyState == 4) {
//                        var img = document.createElement("img");
//                        img.src = request.responseBlob;
//                        document.body.appendChild(img);
                        var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                        QualityHelperControl.content.SilverlightQualityHelper.EventFileProxied(docID, request.responseBlob, request.responseBlob.length);
                    }
                }
                request.send();
            }

            function getFileViaURL(URL) {
                var windowNew = window.open(URL, "_blank", "location=1,status=1,scrollbars=1,resizable=1,width=200,height=200");
            }

            function openDocumentViaCode(docCode) {
                switch (docCode) {
                    case "HELP":
                        var helpDoc = InnovationFoundryJS.DataManager.HelpDoc;
                        var helpDocID = parseInt(helpDoc);
                        if (isNaN(helpDocID))
                            getFileViaURL(helpDoc);
                        else
                            openDocument(helpDocID);
                        break;
                }
            }

            function searchProcedures(searchTerm) {
                var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                QualityHelperControl.content.SilverlightQualityHelper.SearchProceduresCallback(InnovationFoundryJS.DataManager.db_search_procedure_id(searchTerm), searchTerm);
                QualityHelperControl.content.SilverlightQualityHelper.SearchProceduresCallback(InnovationFoundryJS.DataManager.db_search_procedure_name(searchTerm), searchTerm);
                QualityHelperControl.content.SilverlightQualityHelper.SearchProceduresCallback(InnovationFoundryJS.DataManager.db_search_procedure_aliases(searchTerm), searchTerm);
                QualityHelperControl.content.SilverlightQualityHelper.SearchProceduresCallback(InnovationFoundryJS.DataManager.db_search_procedure_description(searchTerm), searchTerm);
                
            }

            function searchDocuments(searchTerm) {
                var QualityHelperControl = document.getElementById("QualityHelperSilverlightControl");
                QualityHelperControl.content.SilverlightQualityHelper.SearchDocumentsCallback(InnovationFoundryJS.DataManager.db_search_document(searchTerm), searchTerm);
            }

            var workerPool = google.gears.factory.create('beta.workerpool');
            workerPool.onmessage = function(a, b, message) {
                alert('Received message from worker ' + message.sender + ': \n' + message.body);
            };
            function startWorker() {
                var childWorkerId = workerPool.createWorkerFromUrl('worker.js');
                workerPool.sendMessage(["origin...3..2..", 1, { helloWorld: "Hello world!"}], childWorkerId);
            }

            function testCaptureBlob() {
                //startAsync();
                var url = './DocReader.axd/23';
                //httpGetAsRequest(url, function(request) {
                    var store = InnovationFoundryJS.DataManager.localStore;
                    var captureUrl = '/captured.txt';
                    var responseBlob = request.responseBlob;

                    store.captureBlob(responseBlob, captureUrl);
                    assertBlobProbablyEqual(store.getAsBlob(captureUrl), responseBlob);
                    //assertEqual('application/octet-stream',
                    assertEqual('image/png', store.getHeader(captureUrl, 'Content-Type'));

                    var contentType = request.getResponseHeader('Content-Type');
                    store.captureBlob(responseBlob, captureUrl, contentType);
                    assertBlobProbablyEqual(store.getAsBlob(captureUrl), responseBlob);
                    assertEqual(contentType, store.getHeader(captureUrl, 'Content-Type'));

                    //               httpGetAsRequest(captureUrl, function(request2) {
                    //                 assertBlobProbablyEqual(responseBlob, request2.responseBlob);
                    //                 assertEqual(contentType, request2.getResponseHeader('Content-Type')); //<---- FAILS HERE
                    //                 completeAsync();
                    //               });
                //});
            }

             //Not Implemented Yet
             //var desktop = google.gears.factory.create('beta.desktop')
             //var notification = desktop.createNotification();
             //notification.title = 'Barbecue on Saturday';
             //notification.icon = 'http://mail.google.com/mail.gif';
             //notification.subtitle = 'Thu Mar 27 1:25pm - 2:25pm';
             //notification.description = 'Hey everyone, looks like great weather this ' +
             //    'weekend so I thought we might get together';
             //notification.displayAtTime = new Date(2008, 5, 27, 14, 0, 0);
             //notification.displayUntilTime = new Date(2008, 5, 27, 14, 0, 15);
             //notification.addAction('View', 'http://mail.google.com/view?id=...');
             //desktop.showNotification(notification);
             //Object.toJSON will cause recursion unless we override toJSON methods see: http://prototypejs.org/learn/json
             //document.write(Object.toJSON(diagram));
             //document.write(Object.toJSON(procedures));
            //document.write(Object.toJSON(connections));

            //This will start everything going
            HideMainSilverlightControl();
            GetDate_ServerTime();
        </script>
        <div id="debug" style="display:none">
        <!-- Runtime errors from Silverlight will be displayed here.
	    This will contain debugging information and should be removed or hidden when debugging is completed -->
	    <div id='errorLocation' style="font-size: small;color: Gray;"></div>
        <%--<div id="debug" style="visibility:visible;display:inline;">--%>
            <table style="width:100%;">
                <tr>
                    <td>
                        ID:</td>
                    <td>
                        <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        &nbsp;</td>
                </tr>
                <tr>
                    <td>
                        File:</td>
                    <td>
                        <asp:FileUpload ID="fileUpload" runat="server" />
                    </td>
                    <td>
                        &nbsp;</td>
                </tr>
                <tr>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:Button ID="btnSave" runat="server" onclick="btnSave_Click" Text="Save" />
                    </td>
                    <td>
                        &nbsp;</td>
                </tr>
            </table>
            <asp:Literal ID="literal" runat="server"></asp:Literal>
            <br />
            Read my source!<input id="Button1" type="button" value="get all" onclick="javascript:GetAll();" />
            <a href="./ResetClient.aspx">Reset</a><br />
            <a href="./FileReader.axd?FileID=aec26455-523a-47be-903a-78eea391c6ed">Test Doc</a>
            <a href="./DocReader.axd/23">Test Doc 2</a>
            <input type="button" onclick="openDocument('6');" value="get 6" />
            <input type="button" onclick="bob();" value="test silverlight"/>    
            <input type="button" onclick="getFileViaGears('23');" value="test blob" />
            <input type="button" onclick="switchMode();" value="switch mode" />
            <input type="button" onclick="ClearAllDocuments();" value="clear doc cache" />
            <input type="button" onclick="ResetDB();" value="reset db" />
            <input type="button" onclick="procedureClicked('QH');" value="internal procedure test" />
            <input type="button" onclick="fill();" value="fill" />
            <input type="button" onclick="createShortcut();" value="shortcut" />
            <input type="button" onclick="startWorker();" value="startworker" />
            <input type="button" onclick="InnovationFoundryJS.DataManager.cache_documents('./DocReader.axd/23')" value="test cache" />
            <input type="button" onclick="InnovationFoundryJS.DataManager.cache_documents('./FileReader.axd?FileID=aec26455-523a-47be-903a-78eea391c6ed')" value="test cache2" />
            <input type="button" onclick="testCaptureBlob();" value="test cache3" />
            
            <img src="./FileReader.axd?FileID=b0688003-2e87-444b-9ffe-8ff9183141e0" />
            <br />tested
        </div>
        <script language="javascript" type="text/javascript">
            if (document.location.href.indexOf("utility") > -1) {
                var debugObj = document.getElementById("debug");
                debugObj.style.visibility = 'visible';
                debugObj.style.display = 'inline';
            }
        </script>
    </form>
    <iframe marginheight="0" marginwidth="0" style="display:none;" id="downloader" width="0" height="0" scrolling="no" frameborder="0"></iframe>
</body>
</html>






